# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import re
import jinja2
import hashlib
import simplejson
import time
import werkzeug.utils
from openerp import tools
from datetime import datetime
import openerp
from openerp import http
from openerp.http import request
from openerp.modules.registry import RegistryManager
from openerp.osv import osv
import zbar
from PIL import Image
from openerp.addons.wechat.enterprise import WxApi, WxApplication, WxTextResponse, WxNewsResponse, WxArticle, WxLink
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
from weixin_enterprise import WeixinEnterprise
ISODATEFORMAT = '%Y-%m-%d'
SUPERUSER_ID = 1

############################################################################################
# 微信企业号"企业小助手"应用消息处理类
# 需要配置wechat.enterprise和wechat.application在data/dftg_corp_weixin.xml文件中
#
class WxAppCropAssistant(WeixinEnterprise):
    _app_xml_id = 'dftg_weixin.weixin_dftg_assistant_application'


    #关注事件
    def on_subscribe(self, req):
        res = super(WxAppCropAssistant, self).on_unsubscribe(req)
        db = RegistryManager.get(request.session.db)
        with closing(db.cursor()) as cr:
            contacts_obj = db.get('weixin.contacts')
            try:
                contacts = contacts_obj.browse(cr, SUPERUSER_ID, int(req.FromUserName))
            except ValueError:
                return res
            if contacts.exists():
                contacts.write({'is_follow': True})
            cr.commit()
        return res

    #取消关注事件
    def on_unsubscribe(self, req):
        res = super(WxAppCropAssistant, self).on_unsubscribe(req)
        db = RegistryManager.get(request.session.db)
        with closing(db.cursor()) as cr:
            contacts_obj = db.get('weixin.contacts')
            try:
                contacts = contacts_obj.browse(cr, SUPERUSER_ID, int(req.FromUserName))
            except ValueError:
                return res
            if contacts.exists():
                contacts.write({'is_follow': False})
            cr.commit()
        return res

    def search_user_point(self, req):
        db = RegistryManager.get(request.session.db)
        with closing(db.cursor()) as cr:
            res_users = db.get('res.users')
            oauth_uid = req.FromUserName
            oauth_id_user_ids = res_users.search(cr, 1, [('oauth_uid', '=', oauth_uid)])
            res_users_objs = res_users.browse(cr, 1, oauth_id_user_ids)
            return "您当前积分 %s" % (str(res_users_objs.point_balance))

    # 发送文本回调
    def on_text(self, req):
        # 默认回复同样的文字
        response_content = u'暂不支持此指令'

        # 发送给odoo bus消息测试（所有用户都会收到），暂时注释
        # db = RegistryManager.get(request.session.db)
        # with closing(db.cursor()) as cr:
        #     user_obj = db.get('res.users')
        #     user_ids = user_obj.search(cr, SUPERUSER_ID, [('oauth_uid', '=', req.FromUserName)])
        #     if user_ids:
        #         user_id = user_ids[0]
        #         user = user_obj.browse(cr, 1, user_id)
        #         db.get('bus.bus').sendone(cr, user_id, 'dftg_message', {'title': user.name + '的通知', 'content': req.Content})

        if req.Content == 'JFCX' or req.Content == '积分查询':
            response_content = self.search_user_point(req)
            return WxTextResponse(response_content, req)

        # 检查临时登录密码，如果找到匹配的，则写入user_id
        re_login_groups = re.match(r'D(\d+)(.*)', req.Content, re.I)
        if re_login_groups and re_login_groups.groups():
            groups = re_login_groups.groups()
            len_groups = len(groups)
            if len_groups > 0:
                temp_password = groups[0]
            if len_groups == 2:
                login = groups[1]
            db = RegistryManager.get(request.session.db)
            oauth_uid = req.FromUserName
            with closing(db.cursor()) as cr:
                weixin_session = db.get('weixin.session')
                session_ids = weixin_session.search(cr, SUPERUSER_ID, [('temp_password', '=', temp_password),
                                                                       ('check_time', '=', None)])
                if session_ids:
                    session_row = weixin_session.browse(cr, SUPERUSER_ID, session_ids[0])
                    res_users = db.get('res.users')
                    if login:
                        #oauth_id_is_admin = False
                        oauth_id_user_ids = res_users.search(cr, 1, [('oauth_uid', '=', oauth_uid)])
                        if oauth_id_user_ids:
                            oauth_id_user_id = oauth_id_user_ids[0]
                            oauth_id_is_admin = res_users.has_group(cr, oauth_id_user_id, 'base.group_erp_manager')
                            if oauth_id_is_admin:
                                user_ids = res_users.search(cr, 1, [('login', '=', login)])
                            else:
                                print u'------ 您没有权限替他人登录'
                        else:
                            print u'------ 您没有绑定账号'
                    elif oauth_uid:
                        user_ids = res_users.search(cr, 1, [('oauth_uid', '=', oauth_uid)])
                    if user_ids:
                        user = res_users.browse(cr, 1, user_ids[0])
                        session_row.write({'user_id': user_ids[0], 'oauth_uid': oauth_uid})
                        cr.commit()
                        db.get('bus.bus').sendone(cr, user_ids[0], 'weixin_login', {'sid': session_row.session_id})
                        response_content = user.name + u' 账号已确认登录'
                    else:
                        response_content = u'用户未找到，需要重新绑定账号'
                else:
                    response_content = u'请打开登录页面或者再次刷新页面'

        # 消息回复不支持
        return WxTextResponse(response_content, req)
    
    def _generate_image_path(self,  file):
        cr, context, pool = request.cr, request.context, request.registry
        direction = pool.get('ir.config_parameter').get_param(cr, SUPERUSER_ID, 'dftg_ext.editor_image_folder')
        if direction:
            if not os.path.exists(direction) or not os.path.isdir(direction):
                raise ValueError(u'错误，系统配置中获取到的路径不不是文件夹或不存在')
        else:
            main_direction = tools.config.filestore(cr.dbname)
            img_direction = 'weixin_media'
            first_direction = os.path.join(img_direction, datetime.now().strftime(ISODATEFORMAT))
            if not os.path.exists(os.path.join(main_direction, first_direction)):
                os.makedirs(os.path.join(main_direction, first_direction))
            filename = os.path.join(first_direction,file)
        return filename, os.path.join(main_direction, filename)
    
    def judge_qrcode_out_going(self, file_name):
        scanner = zbar.ImageScanner()
        # 设置对象属性
        scanner.parse_config('enable')

        # 打开含有二维码的图片
        img = Image.open(file_name).convert('L')
        # 获取图片的尺寸
        width, height = img.size
        # 建立zbar图片对象并扫描转换为字节信息
        qrCode = zbar.Image(width, height, 'Y800', img.tobytes())
        scanner_result = scanner.scan(qrCode)
        data = ''
        if scanner_result:
            for s in qrCode:
                data += s.data
            # 删除图片对象
            del img
            # 输出解码结果
        return data
        
    # def on_image(self, req):
    #     cr, context, pool = request.cr, request.context, request.registry
    #     file_path = self._generate_image_path(req.MediaId)
    #     self.wxapi.download_media(req.MediaId,  file_path[1])
    #     qrcode_value = self.judge_qrcode_out_going(file_path[1])
    #     if qrcode_value:
    #         if '/wx/stock/picking_view/' in qrcode_value:
    #             qrcode_picking_list = qrcode_value.split('/wx/stock/picking_view/')
    #             picking_id = qrcode_picking_list[1] and int(qrcode_picking_list[1])
    #             picking_row = pool.get('stock.picking').browse(cr, 1, picking_id, context=context)
    #             result = pool.get('stock.picking').stock_picking_sign(cr, 1, picking_id, context=None)
    #             if result and not picking_row.image_sign_path:
    #                 picking_row.write({'image_sign_path': file_path[0]})
    #                 response_content = u'上传签收图片成功!'
    #             else:
    #                 if picking_row.image_sign_path:
    #                     os.remove(os.path.join(tools.config.filestore(cr.dbname), picking_row.image_sign_path))
    #                 picking_row.write({'image_sign_path': file_path[0]})
    #                 response_content = u'覆盖签收图片成功!'
    #         else:
    #             response_content = u'图片中二维码无效！'
    #     else:
    #         response_content = u'图片中不包含二维码！'
    #     return WxTextResponse(response_content, req)

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


################################################################
# 企业小助手应用微信控制器
#
class WeixinAppAssistantController(http.Controller):
    weixin_app = None

    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxAppCropAssistant()

    #微信回调入口网址
    @http.route('/weixin/app/assistant', auth='public')
    def weixin(self, **kw):
        result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
        return result

class code_password_export_wizard(osv.osv):
    _inherit = 'code.password.export.wizard'

    def send_password_to_user(self,cr,uid,password,user_id,context =None):
        wx_api_sed_text = WxAppCropAssistant()
        contact_id = self.pool.get('weixin.contacts').search(cr, uid, [('odoo_user_id', '=', user_id)],
                                                             context=context)
        if contact_id:
            wx_api_sed_text.wxapi.send_text(password, wx_api_sed_text.APP_ID, safe="0", touser=str(contact_id[0]))
        return True

class work_overtime_leave(osv.osv):
    _inherit = 'work.overtime.leave'

    def send_message_to_approve(self, cr, uid, ids, context=None):
        return_vals = super(work_overtime_leave, self).send_message_to_approve(cr, uid, ids, context=context)
        wx_api_sed_text = WxAppCropAssistant()
        for work_overtime_row in self.browse(cr, uid, ids, context=context):

            contact_id = self.pool.get('weixin.contacts').search(cr, uid, [('odoo_user_id', '=',
                                                                            work_overtime_row.approver_user_id.id)],
                                                                 context=context)
            type_dict = dict(work_overtime_row._fields.get('type').selection)
            type_http = dict([('changeworkday', 'leave'), ('overtime', 'work')])
            if contact_id and work_overtime_row.type in type_http:
                send_message = u"<a href=\"http://%s/wx/hr/%s/unapprove\">您部门的员工%s,提交了一份时间是%s时长%s小时%s的申请,请及时处理!</a>"%(
                                            request.httprequest.host,
                                            type_http.get(work_overtime_row.type),
                                            work_overtime_row.user_id.name, work_overtime_row.date,
                                           work_overtime_row.hour_qty,  type_dict.get(work_overtime_row.type))
                wx_api_sed_text.wxapi.send_text(send_message, wx_api_sed_text.APP_ID, safe="0", touser=str(contact_id[0]))
        return return_vals


class sale_order(osv.osv):
    _inherit = 'sale.order'

    def send_message(self, cr, uid, send_uid, send_message, context=None):
        wx_api_sed_text = WxAppCropAssistant()
        session_obj = self.pool.get('im_chat.session')
        contact_id = self.pool.get('weixin.contacts').search(cr, uid, [('odoo_user_id', '=', send_uid)],
                                                             context=context)
        if contact_id:
            wx_api_sed_text.wxapi.send_text(send_message, wx_api_sed_text.APP_ID, safe="0", touser=str(contact_id[0]))
        model_data_obj = self.pool.get('ir.model.data')
        user_id = model_data_obj.xmlid_to_res_id(
            cr, SUPERUSER_ID, 'dftg_ext.notify_user_id')
        session_info = session_obj.session_get(cr, user_id, send_uid, context=context)
        session_obj.update_state(cr, user_id, session_info.get('uuid'), 'open', context=None)
        session_id = session_obj.search(cr, SUPERUSER_ID, [('uuid', '=', session_info.get('uuid'))],
                                        order='write_date desc')
        if session_id:
            self.pool.get('im_chat.message').post(cr, SUPERUSER_ID, from_uid=user_id,
                                                  uuid=session_info.get('uuid'),
                                                  message_type='message', message_content=send_message, context=context)

    def send_wexin_message(self, cr, uid, send_uid, send_message, context=None):
        wx_api_sed_text = WxAppCropAssistant()
        contact_id = self.pool.get('weixin.contacts').search(cr, uid, [('odoo_user_id', '=', send_uid)],
                                                             context=context)
        if contact_id:
            wx_api_sed_text.wxapi.send_text(send_message, wx_api_sed_text.APP_ID, safe="0", touser=str(contact_id[0]))
            
    def send_odoo_message(self, cr, uid, send_uid, send_message, context=None):
        session_obj = self.pool.get('im_chat.session')
        model_data_obj = self.pool.get('ir.model.data')
        user_id = model_data_obj.xmlid_to_res_id(
            cr, SUPERUSER_ID, 'dftg_ext.notify_user_id')
        session_info = session_obj.session_get(cr, user_id, send_uid, context=context)
        session_obj.update_state(cr, user_id, session_info.get('uuid'), 'open', context=None)
        session_id = session_obj.search(cr, SUPERUSER_ID, [('uuid', '=', session_info.get('uuid'))],
                                        order='write_date desc')
        if session_id:
            self.pool.get('im_chat.message').post(cr, SUPERUSER_ID, from_uid=user_id,
                                                  uuid=session_info.get('uuid'),
                                                  message_type='message', message_content=send_message, context=context)

